package com.smartmedi.ai.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.smartmedi.ai.constants.RecordExtractionPrompt;
import com.smartmedi.ai.exception.ErrorCode;
import com.smartmedi.ai.exception.ThrowUtils;
import com.smartmedi.ai.service.RecordExtractionService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Map;

@Service
public class RecordExtractionServiceImpl implements RecordExtractionService {

    private static final Logger logger = LoggerFactory.getLogger(RecordExtractionServiceImpl.class);
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Resource
    private ChatClient chatClient;

    @Resource
    private Advisor loveAppRagCloudAdvisor;

    /**
     * 大模型语义匹配提取json
     * @param textContent 文本内容
     * @return json
     */
    @Override
    public Map<String, Object> processSingleStep(String textContent) {
        ThrowUtils.throwIf(textContent == null, ErrorCode.PARAMS_ERROR);
        String systemPrompt = RecordExtractionPrompt.SYSTEM_PROMPT;

        try {
            String text = chatClient.prompt()
                    .system(systemPrompt)
                    .advisors(loveAppRagCloudAdvisor)
                    .user(textContent)
                    .call()
                    .chatResponse().getResult().getOutput().getText();
            
            // 解析JSON响应
            try {
                // 尝试将文本解析为Map
                @SuppressWarnings("unchecked")
                Map<String, Object> jsonResult = objectMapper.readValue(text, Map.class);
                return jsonResult;
            } catch (JsonProcessingException e) {
                logger.error("JSON解析失败: {}", e.getMessage());
                // 如果解析失败，返回原始文本
                return Collections.singletonMap("result", text);
            }
        } catch (Exception e) {
            logger.error("处理请求时发生错误: {}", e.getMessage());
            ThrowUtils.throwIf(true, ErrorCode.SYSTEM_ERROR, "AI处理失败: " + e.getMessage());
            // 以下代码不会执行，但需要返回以满足编译要求
            return Collections.emptyMap();
        }
    }
}
